<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div>
    hello world! <span id="name"></span>
    <div><button id="getName">get name</button></div>
</div>
<script>
    //将token从浏览器cookie中取出
    function getCookie(name) {
        var cookieValue = "";
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = $.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURI(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    //公共的加了token的ajax函数
    function tokenAjax($, url, type, data, cb) {
        var tk = getCookie("token");
        $.ajax({
            url: url,
            data: data,
            type: type,
            dataType: "json",
            headers: {token:  tk},
            success: function(res) {
                cb(true, res);
            },
            error: function(xhr, status, error) {
                //xhr.responseText, xhr. status
                cb(true, xhr);
            }
        });
    }

    //回调函数, 因为ajax是异常加载, 并没有返回值,所以需要一个回调函数
    function callback(status, res) {
        if (status){
            if (res.code === 0){
                $("#name").text(res.msg)
            }else{
                alert(res.msg);
                window.location = "login"
            }
        }else {
            console.log(res.status, res.responseText);
            alert(res.status + res.responseText)
        }
    }

    //点击事件, 传入ajax返回结果后需要执行的函数
    $("#getName").click(function(){
       tokenAjax($, "index", "POST", {}, callback);
    })

</script>
</body>
</html>